function hfile = srf_Transform(hfile, mat44)
% SRF::Transform  - apply 4x4 quaternion to coordinates/normals
%
% FORMAT:       [srf] = srf.Transform(mat44)
%
% Input fields:
%
%       mat44       4x4 affine transformation matrix
%
% Output fields:
%
%       srf         altered object

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'srf') || ...
   ~isa(mat44, 'double') || ...
    numel(size(mat44)) ~= 2 || ...
    any(size(mat44) ~= 4) || ...
    any(isinf(mat44(:)) | isnan(mat44(:)))
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);

% apply transformations
v = bc.VertexCoordinate;
v = v - repmat(bc.MeshCenter, [size(v, 1), 1]);
v(:, 4) = 1;
n = bc.VertexNormal;
v = (mat44 * v')';
n = (mat44(1:3, 1:3) * n')';
n = n ./ repmat(sqrt(sum(n .* n, 2)), [1, 3]);
n(any(isinf(n), 2) | any(isnan(n), 2), :) = sqrt(3);

% put back in hfile
bc.VertexCoordinate = v(:, 1:3) + repmat(bc.MeshCenter, [size(v, 1), 1]);
bc.VertexNormal = n;
bvqxfile_setcont(hfile.L, bc);
